<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/9 0009
 * Time: 16:35
 */

namespace app\admin\model;

use app\common\model\BaseModel;

class Tenantdistributionlinkstore extends BaseModel
{
    const is_dis_0 = 0;   //是否支持配送 0不支持  1支持
    const is_dis_1 = 1;   //是否支持配送 0不支持  1支持


    public function getStore(){
        return $this->hasOne('store','id','storeId');
    }


    public function getCurrentTenantDistrbutionStore($data){
        return self::where([
            'storeId'=>$data['storeId'],
            'tenantId'=>$data['tenantId']
        ])->find();
    }

    public function findCureeLinkStore($tenantDistributionId,$storeId){
        return self::where(['tenantDistributionId'=>$tenantDistributionId,
        'storeId'=>$storeId
        ])->find();
    }


    public function add_or_update_store($selfTypeStoreIdArr,$type_id,$packingCharge){
        $tdtypeModel = new Tenantdistributiontype();

        $type = $tdtypeModel->findTdtType($type_id);

        $tdtStores = self::where('tenantDistributionId',"=",$type_id)->select();

        if($selfTypeStoreIdArr && !empty($selfTypeStoreIdArr) ){
            foreach ($selfTypeStoreIdArr as $item){
                $tdtStore = self::where('storeId',"=",$item)
                    ->where("tenantDistributionId",'=',$type_id)
                    ->where("tenantId",'=',$type['tenantId'])
                    ->find();

               if($tdtStore && !empty($tdtStore)){
                   self::where('storeId',"=",$item)
                       ->where("tenantDistributionId",'=',$type_id)
                       ->where("tenantId",'=',$type['tenantId'])
                       ->update(['status'=>self::STATUS_VALID]);
               }else{
                    $this->insertGetId([
                        'storeId'=>$item,
                        'tenantDistributionId'=>$type_id,
                        'tenantId'=>$type['tenantId'],
                        'packingCharge'=>$packingCharge,
                        'status'=>self::STATUS_VALID,
                    ]);
               }
            }
            self::where('storeId',"not in",$selfTypeStoreIdArr)
                ->where("tenantDistributionId",'=',$type_id)
                ->where("tenantId",'=',$type['tenantId'])
                ->update(['status'=>self::STATUS_INVALID]);
        }
        return true;
    }

}